<script lang="ts" setup>
import { label } from '@unovis/ts/components/axis/style';
import OpenAPIClientAxios from 'openapi-client-axios';
import { useRouter } from 'vue-router';
import { ref } from "vue";
import { ElTable, ElTableColumn,ElButton,ElDropdown, ElDropdownMenu, ElDropdownItem,ElLink} from 'element-plus';
import { flattenDiagnosticMessageText } from 'typescript';
import transferModal from '@/components/taskmanager/taskTransfer.vue';



  const api = new OpenAPIClientAxios({
    definition:"http://clusters.luo980.com:11004/apidocs.json",
    axiosConfigDefaults: {
      baseURL: 'http://clusters.luo980.com:11004'
    }
  })


const client = await api.init();

// 修改为
// async function initClient() {
//   const client = await api.init();
//   return client;
// }
// const client = initClient();


  async function fetchGroups() {
    const groups = []
    const taskDistribution = ref([
      { type: 'command', count: 0 },
      { type: 'wasm', count: 0 },
      { type: 'pod', count: 0 },
      { type: 'device', count: 0 },
    ]);

    console.log(client)
    try{
      const response = await client['Get groups']({"Namespace":"test"})
      const groupData = response.data.items;
      console.log(groupData);

      for (const group of groupData) {
        for(const action of group.spec.actions){
          for(const runtime of action.runtimes){
            const runningType = runtime.type
            console.log(runningType)
            if(runningType == "command"){
              for(const data of taskDistribution.value){

                if(data.type == "command"){
                    data.count +=1
              }
              }
            }else if(runningType == "wasm"){
              for(const data of taskDistribution.value){

                if(data.type == "wasm"){
                    data.count +=1
                }
              }
            }else if(runningType == "pod"){
                for(const data of taskDistribution.value){

                  if(data.type == "pod"){
                      data.count +=1
                }
              }
            }else if(runningType == "device"){
                for(const data of taskDistribution.value){

                  if(data.type == "device"){
                      data.count +=1
                }
              }
            }
          }
          

        }
      }
    }catch (error) { console.error(error); }
    return taskDistribution.value
  }  

  async function fetchWorkflows() {
    const tasks = []
  // 这里应该是调用接口的代码，返回工作流列表
    //获取一个组


    try{
      const response = await client['Get tasks']({"Namespace":"test"})
      const workflowData = response.data.items;


      for (const workflow of workflowData) {
        const runningTime = calculateTimeDifference(workflow.status.start, workflow.status.last_time);
        tasks.push({
          workflowName: workflow.name,
          taskName: "-",
          status: workflow.status.phase,
          processingNode: "-",
          runningNode: "-",
          createTime: workflow.status.create,
          latestUpdateTime: workflow.status.last_time,
          runningTime: runningTime,
          belongto: ""
        });

        const groups= workflow.status.groups;
        console.log(groups)
        for (let groupName in groups) {
          const groupInfo = groups[groupName]
          console.log(groupInfo);
          const response1 = await client['Get group']({"Namespace":"test","Name":groupInfo.Name})

          const groupData = response1.data
          const runningTime1 = calculateTimeDifference(groupData.status.start, groupData.status.last_time);
          tasks.push({
            workflowName: "-",
            taskName: groupData.name,
            status: groupData.status.phase,
            processingNode: "Scheduler",
            runningNode: groupData.status.node,
            createTime: groupData.status.create,
            latestUpdateTime: groupData.status.last_time,
            runningTime: runningTime1,
            belongto: groupData.labels.belong
          });
        }
      }
    }catch (error) { console.error(error); }
    // client['Get tasks']()
    // .then(response => {
    //   console.log("group data" + response.data)
    //   // 使用Object.entries()获取键值对数组
    //   const workflowData = response.data.Items
    //   console.log(workflowData.length)
    //   // 输出键值对
    //   workflowData.forEach(workflow => {
    //     const runningTime = calculateTimeDifference(workflow.status.start,workflow.status.last_time)
    //     console.log(workflow)
    //     tasks.push({
    //       workflowName: workflow.spec.name,
    //       taskName: "-",
    //       status: "Running",
    //       processingNode: "-",
    //       runningNode: "-",
    //       createTime: workflow.status.start,
    //       latestUpdateTime: workflow.status.last_time,
    //       runningTime: runningTime,
    //       belongto: ""
    //     })
    //     console.log(tasks)
    //     const groupData = workflow.spec.groups
    //     groupData.forEach(group => {
    //       const runningTime1 = calculateTimeDifference(group.status.start,group.status.last_time)
    //       tasks.push({
    //         workflowName: "-",
    //         taskName: group.spec.name,
    //         status: "Running",
    //         processingNode: "-",
    //         runningNode: "-",
    //         createTime: group.status.start,
    //         latestUpdateTime: group.status.last_time,
    //         runningTime: runningTime1,
    //         belongto: ""
    //       })
    //     })
    //   });
    // })
    // .catch(error => console.error(error));
  // 模拟数据
  return tasks
}

function calculateTimeDifference(timestamp1: string, timestamp2: string): string {
  // 将字符串转换为日期对象
  const date1: Date = new Date(timestamp1);
  const date2: Date = new Date(timestamp2);

  // 计算时间差（毫秒）
  const timeDifference: number = date2.getTime() - date1.getTime();

  // 将毫秒转换为秒
  const totalSeconds: number = Math.floor(timeDifference / 1000);

  // 将秒转换为分钟和秒
  const minutes: number = Math.floor(totalSeconds / 60);
  const seconds: number = totalSeconds % 60;

  // 返回格式化的字符串
  return `${minutes} min${seconds} s`;
}





// 合并工作流和任务，并格式化输出
async function mergeWorkflowsAndTasks() {
  const workflows = await fetchWorkflows();

  console.log(workflows)
  // 分组
  // const groupedByBelongto = workflows.reduce((acc, item) => {
  //   if (!item.belongto) {
  //     // 独立的工作流
  //     acc[item.workflowName] = acc[item.workflowName] || [];
  //     acc[item.workflowName].push(item);
  //   } else {
  //     // 属于某个工作流的任务
  //     acc[item.belongto] = acc[item.belongto] || [];
  //     acc[item.belongto].push(item);
  //   }
  //   return acc;
  // }, {});

  // // 排序并格式化输出
  // const sortedAndFormatted = Object.keys(groupedByBelongto)
  //   .sort() // 根据工作流名称排序
  //   .map(workflowName => {
  //     // 对每个分组内的元素进行排序，例如按 createTime 排序
  //     const sortedGroup = groupedByBelongto[workflowName].sort((a, b) => a.createTime.localeCompare(b.createTime));
  //     return sortedGroup;
  //   })
  //   .flat(); // 将所有分组展平成一个数组
  //   console.log(sortedAndFormatted)
  return workflows

}
  const showList = ref()
  let interval : any
  const taskDistribution = ref()
  onMounted(() => {
        // 初始加载数据
      mergeWorkflowsAndTasks().then(res => {
        showList.value = res;
        console.log(showList.value.length);
      });

      // 设置定时器，每 3 秒刷新一次数据
      interval = setInterval(async () => {
        try {
          taskDistribution.value = await fetchGroups();
          console.log("taskds"+taskDistribution.value[0].type)
          const res = await mergeWorkflowsAndTasks();
          showList.value = res;
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      }, 10000);
    });

    onBeforeUnmount(() => {
      // 组件销毁前清除定时器
      if (interval) {
        clearInterval(interval);
      }
    });



// const taskDistribution = ref([
//   { type: 'command', count: 0 },
//   { type: 'wasm', count: 0 },
//   { type: 'pod', count: 0 },
//   { type: 'device', count: 0 },
// ]);

const filteredWorkflows = ref([
  {workflowName:"wk1", taskName:"-",status:"Running",processingNode:"node1",runningNode:"node1-ing",createTime:"xxx",latestUpdateTime:"xxx-x",runningTime:"99min",belongto:""},
  {workflowName:"-", taskName:"ts1",status:"Migrated",processingNode:"node1",runningNode:"node1-ing",createTime:"xxx",latestUpdateTime:"xxx-x",runningTime:"99min",belongto:"wk1"},
  {workflowName:"-", taskName:"ts2",status:"Migrating",processingNode:"node1",runningNode:"node1-ing",createTime:"xxx",latestUpdateTime:"xxx-x",runningTime:"99min",belongto:"wk1"},
  {workflowName:"-", taskName:"ts3",status:"Init",processingNode:"node1",runningNode:"node1-ing",createTime:"xxx",latestUpdateTime:"xxx-x",runningTime:"99min",belongto:"wk1"},
  {workflowName:"wk2", taskName:"-",status:"Running",processingNode:"node1",runningNode:"node1-ing",createTime:"xxx",latestUpdateTime:"xxx-x",runningTime:"99min",belongto:""},
  {workflowName:"-", taskName:"ts4",status:"Running",processingNode:"node1",runningNode:"node1-ing",createTime:"xxx",latestUpdateTime:"xxx-x",runningTime:"99min",belongto:"wk2"}
])

const clusterTypeSelectedListResources = [
  {
    title: '全部',
    value: 0
  },
  {
    title: '云',
    value: 1
  },
  {
    title: '边',
    value: 2
  },
  {
    title: '端',
    value: 3
  }
];


const clusterType = ref(0);
const clusterSelectedId = ref('');






//三角形小组件
let pickup = false
function clickUp(){
  const picker = document.getElementById('arr1');

  if(pickup == false){
    picker.style.setProperty('border-bottom', '15px solid blue');
    picker.style.setProperty('border-top', '0px solid blue');
    //picker.style.border-bottom ="15px solid blue";
    //picker.style.border-top ="0px solid blue";
    pickup = true
  }else{
    picker.style.setProperty('border-bottom', '0px solid blue');
    picker.style.setProperty('border-top', '15px solid blue');
    picker.style.setProperty('padding-top', '-35px');
    pickup = false
  }
}

//表格
function statusClass(status: string) {
  return status === 'Running'
    ? 'bg-green-500'
    : status === 'Init'
    ? 'bg-purple-500'
    : status === 'Migrated'
    ? 'bg-orange-500'
    : status === 'Pending'
    ? 'bg-gray-500'
    : status === "DeployCheck" || status === "ReadyToDeploy"
    ? 'bg-yellow-500'
    : status === "Error"
    ? 'bg-red-500'
    : status === "Succeeded"
    ? 'bg-blue-500'
    : 'bg-pink-500';
}
const tableLable = ref([
    {
      prop:"workflowName",
      width:"160",
      label:"工作流名称"
    },
    {
      prop:"taskName",
      width:"160",
      label:"任务名称"
    },
    {
      prop:"status",
      width:"80",
      label:"状态"
    },
    {
      prop:"processingNode",
      width:"100",
      label:"处理节点"
    },
    {
      prop:"runningingNode",
      width:"100",
      label:"运行节点"
    },
    {
      prop:"createTime",
      width:"200",
      label:"创建时间"
    },
    {
      prop:"lastUpdateTime",
      width:"200",
      label:"最近更新时间"
    },
    {
      prop:"runningTime",
      width:"80",
      label:"运行时间"
    }
])


interface MyDropdownInterface {
[key: string]: boolean; // 假设我们只存储布尔值
}
const dropdownOpen = ref<MyDropdownInterface>({})

function handleOption1(workflow) {
      // 处理选项1的逻辑，rowData 是当前行的数据
      console.log('Option 1 clicked', workflow);
    }

function handleOption4(workflow) {
      // 处理选项2的逻辑，rowData 是当前行的数据
      console.log('Option 2 clicked', workflow);
    }


//查看任务详情
function handleOption3(workflow) {
      // 处理选项3的逻辑，rowData 是当前行的数据
      console.log('Option 3 clicked', workflow);
      checkTaskDetail(workflow.taskName)
    }

const showDialog = ref(false) 
// 定义响应式变量
const formData = ref({
  transfer_type: '',
  target_type: '',
});
//任务迁移功能唤醒
function handleOption2(workflow) {
      // 处理选项3的逻辑，rowData 是当前行的数据
      showDialog.value = true
    }


// 使用 workflow 的唯一标识来控制每个下拉菜单的显示
function showOptions(k:string){
  console.log("before")
  console.log(...Object.entries(dropdownOpen));

  let flag = false
  if (k in dropdownOpen.value){
    if(dropdownOpen.value[k]){
      flag = false
    }else{
      flag = true
    }
    // 将所有值设置为false
    for(let key in dropdownOpen.value){
      if(!dropdownOpen.hasOwnProperty(key)){
        dropdownOpen.value[key] = false
      }
      
    }

    dropdownOpen.value[k] = flag

    // dropdownOpen.value[k] = !dropdownOpen.value[k]

  }else{
        // 将所有值设置为false
    for(let key in dropdownOpen.value){
      if(!dropdownOpen.hasOwnProperty(key)){
        dropdownOpen.value[key] = false
      }
      
    }
    dropdownOpen.value[k] = true
  }
  console.log("after")
  console.log(...Object.entries(dropdownOpen));
  
  
}

function generateKey(item) {
      // 使用 workflowName 和 taskName 组合成一个唯一键
      return `${item.workflowName}-${item.taskName}`;
}


const router = useRouter();
function checkTaskDetail(taskName:string){
    // 动态加载组件，并传递参数
    if(taskName == "-"){
       console.log(123123)
    }else{
      router.push({path:'./task_info',query:{taskName:taskName}})
      console.log(`Loading details for taskId: ${taskName}`);
      //window.location.href = './task_info?${taskName}'; // 跳转到指定页面
    }

    
}




</script>

<template>
  <v-container>
    <v-row>
      <v-col>
        <v-select
          v-model="clusterType"
          label="集群类型选择"
          :items="clusterTypeSelectedListResources"
        />
      </v-col>

      <v-col>
        <v-select
          v-model="clusterSelectedId"
          label="集群名选择"
          :disabled="isClusterSelectDisabled"
          :items="clusterSelectedListResources"
        />
      </v-col>
    </v-row>
    <div class="showInfo grid grid-cols-4 ">
      <div class="subTitle">
        <p>运行中的任务分布</p>
        <div class="pickup">
          <span id="arr1" class="arrUp" @click="clickUp" ></span>
          <!-- <span class="arrDown" @click="clickDown" :style="{ 'border-top-color': color2 }"></span> -->
        </div>
      </div>
      
      <div class="showType">
          <div
            v-for="item in taskDistribution"
            :key="item.type"
            class="taskType flex flex-col items-center justify-center bg-blue-500 text-white rounded-full w-32 h-32 shadow-md cursor-pointer">
            <p class="text-2xl font-bold">{{ item.count }}</p>
            <p class="text-sm">{{ item.type }}</p>
          </div>
      </div>
      
      <div class="subTitle">
        <p>工作流</p>
        <div class="pickup">
          <span id="arr2" class="arrUp" @click="clickUp2" ></span>
          <!-- <span class="arrDown" @click="clickDown" :style="{ 'border-top-color': color2 }"></span> -->
        </div>
      </div>
      <div class="workflow">
        <table class="table-auto w-full border-collapse border border-gray-300">
          <thead>
            <tr class="bg-gray-100">
              <th class="border p-2"></th>
              <th class="border p-2">工作流名称</th>
              <th class="border p-2">任务名称</th>
              <th class="border p-2">状态</th>
              <th class="border p-2">处理节点</th>
              <th class="border p-2">运行节点</th>
              <th class="border p-2">创建时间</th>
              <th class="border p-2">最近更新时间</th>
              <th class="border p-2">已运行时间</th>
              <th class="border p-2">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="workflow in showList" :key="generateKey(workflow)">
              <td class="border p-2"><input type="radio"></td>
              <td class="border p-2" >{{ workflow.workflowName }}</td>
              <td class="border p-2" @click="checkTaskDetail(workflow.taskName)">{{ workflow.taskName }}</td>
              <td class="border p-2">
                <span
                  :class="statusClass(workflow.status)"
                  class="px-2 py-1 rounded-full text-white"
                >
                  {{ workflow.status }}
                </span>
              </td>
              <td class="border p-2">{{ workflow.processingNode }}</td>
              <td class="border p-2">{{ workflow.runningNode }}</td>
              <td class="border p-2">{{ workflow.createTime }}</td>
              <td class="border p-2">{{ workflow.latestUpdateTime }}</td>
              <td class="border p-2">{{ workflow.runningTime }}</td>
              <td class="border p-2">
                <button class="text-blue-500" id="dropdowntrigger" @click="showOptions(generateKey(workflow))">...</button>
                <div class="dropdownmenu">
                  <ul v-if="dropdownOpen[generateKey(workflow)]" class="dropdown-content">
                    <li @click="handleOption1(workflow)">取消任务</li>
                    <li @click="handleOption2(workflow)">迁移任务</li>
                    <li @click="handleOption3(workflow)">查看详情</li>
                    <li @click="handleOption4(workflow)">任务日志</li>
                  </ul>
                </div>
              </td>
            </tr>
          </tbody>
          
          <transfer-modal v-if="showDialog" v-model="formData" class="dialog"  @close="showDialog = false">

          </transfer-modal>
        </table>

            
          
      

      </div>
      <div style="height: 300px;display: block;">

      </div>
        <!-- <div style="height: 500px;">
          <el-table :data="showList" border style="width: 100%">
            <el-table-column
              v-for="(item, index) in tableLable"
              :key="item.prop"
              :prop="item.prop"
              :width="item.width"
              :label="item.label"
              align="center">
            </el-table-column>

            <el-table-column label="操作">
              <template #default="scope">
                <el-dropdown placement="top" trigger="click">
                  <span class="el-dropdown-link">
                    ····<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleOption1(scope.row)">取消任务</el-dropdown-item>
                      <el-dropdown-item @click="handleOption2(scope.row)">迁移任务</el-dropdown-item>
                      <el-dropdown-item @click="handleOption3(scope.row)">查看详情</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div> -->
    </div>
  </v-container>
</template>
<style>
.pickup {
  height: 30px;
  margin-top: -15px;
  margin-left: auto;
  margin-right:5%;
}
.showInfo {
  display: flex;
  flex-direction: column;
}
.subTitle {
  margin-top: 20px;
  position: relative;
  left: 0;
  border: #000 1px solid;
  display:flex;
  width: 100%;
  height: 30px;
}
.taskType {
  display: inline-flex;
  margin: auto;
  align-items: center;
}
.showType {
  position: relative;
  border: #000 1px solid;
  display:flex;
  width: 100%;
  height: 200px;
  align-items: center;
}
.arrUp {
  width: 0;
  height: 0;
  border-right: 15px solid transparent;
  border-left: 15px solid transparent;
  border-bottom: 15px solid blue;
  cursor: pointer;
}

.arrDown {
  width: 0;
  height: 0;
  border-right: 5px solid transparent;
  border-left: 5px solid transparent;
  border-top: 5px solid gray;
  cursor: pointer;
}
ul {
  position: absolute;
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: block;
}

li {
  padding: 8px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
}
.dialog {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
